// 管理员界面JavaScript

let currentPage = 'dashboard';
let usersData = [];

// 配置marked选项
if (typeof marked !== 'undefined') {
    marked.setOptions({
        breaks: true,
        gfm: true,
        sanitize: false
    });
}

// Markdown渲染辅助函数（支持数学公式）
function renderMarkdown(text) {
    if (!text) return '';
    if (typeof marked !== 'undefined') {
        return marked.parse(text);
    }
    return text;
}

// 渲染数学公式
function renderMath(element) {
    if (typeof window.renderMathInElement !== 'undefined' && typeof katex !== 'undefined') {
        try {
            window.renderMathInElement(element, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('数学公式渲染失败:', e);
        }
    }
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('管理员页面已加载');
    
    // 初始化
    init();
});

function init() {
    // 设置导航
    setupNavigation();
    
    // 加载数据
    loadDashboardData();
    loadUsersData();
    
    // 设置图片上传
    setupImageUploads();
    
    // 设置登出按钮
    document.getElementById('logoutBtn').addEventListener('click', function() {
        if (confirm('确定要退出登录吗？')) {
            // 调用登出API
            fetch('/api/admin/logout', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = '/admin-login';
                }
            })
            .catch(error => {
                console.error('登出失败:', error);
                window.location.href = '/admin-login';
            });
        }
    });
}

// 设置导航
function setupNavigation() {
    document.querySelectorAll('.nav-item').forEach(item => {
        item.addEventListener('click', function() {
            const page = this.getAttribute('data-page');
            switchPage(page);
            
            // 更新导航状态
            document.querySelectorAll('.nav-item').forEach(i => i.classList.remove('active'));
            this.classList.add('active');
        });
    });
}

// 切换页面
function switchPage(page) {
    currentPage = page;
    
    // 隐藏所有页面
    document.querySelectorAll('.page').forEach(p => p.classList.remove('active'));
    
    // 显示当前页面
    const currentPageElement = document.getElementById(page + 'Page');
    if (currentPageElement) {
        currentPageElement.classList.add('active');
    }
    
    // 更新页面标题
    const titles = {
        'dashboard': '仪表盘',
        'users': '用户管理',
        'statistics': '数据统计',
        'questions': '题目管理'
    };
    
    document.getElementById('pageTitle').textContent = titles[page] || '管理员后台';
    
    // 根据页面加载数据
    if (page === 'dashboard') {
        loadDashboardData();
    } else if (page === 'users') {
        loadUsersData();
    } else if (page === 'statistics') {
        loadStatisticsData();
    } else if (page === 'questions') {
        loadQuestionsData();
        loadCategoriesForForm();
    }
}

// 加载仪表盘数据
function loadDashboardData() {
    fetch('/api/admin/dashboard')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('totalUsers').textContent = data.total_users || 0;
                document.getElementById('totalQuizCount').textContent = data.total_quiz_count || 0;
                document.getElementById('totalScore').textContent = data.total_score || 0;
                
                const avgScore = data.total_quiz_count > 0 
                    ? Math.round(data.total_score / data.total_quiz_count) 
                    : 0;
                document.getElementById('avgScore').textContent = avgScore;
                
                // 显示最近活动
                displayRecentActivity(data.recent_activities || []);
            }
        })
        .catch(error => {
            console.error('加载仪表盘数据失败:', error);
        });
}

// 加载用户数据
function loadUsersData() {
    fetch('/api/admin/users')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                usersData = data.users || [];
                displayUsersTable(usersData);
            }
        })
        .catch(error => {
            console.error('加载用户数据失败:', error);
        });
}

// 加载统计数据
function loadStatisticsData() {
    fetch('/api/admin/statistics')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                document.getElementById('todayUsers').textContent = data.today_users || 0;
                document.getElementById('activeUsers').textContent = data.active_users || 0;
                document.getElementById('todayQuiz').textContent = data.today_quiz || 0;
                document.getElementById('avgQuiz').textContent = data.avg_quiz || 0;
                document.getElementById('maxScore').textContent = data.max_score || 0;
                document.getElementById('minScore').textContent = data.min_score || 0;
                
                console.log('统计数据已加载:', data);
            } else {
                console.error('加载统计失败:', data.message);
            }
        })
        .catch(error => {
            console.error('加载统计数据失败:', error);
        });
}

// 显示用户表格
function displayUsersTable(users) {
    const tbody = document.getElementById('usersTableBody');
    
    if (users.length === 0) {
        tbody.innerHTML = '<tr><td colspan="7" class="no-data">暂无用户数据</td></tr>';
        return;
    }
    
    tbody.innerHTML = users.map(user => `
        <tr>
            <td><strong>${user.username}</strong></td>
            <td>${user.email}</td>
            <td>${user.created_at || '未知'}</td>
            <td>${user.last_login || '从未登录'}</td>
            <td>${user.quiz_count || 0}</td>
            <td><strong>${user.score || 0}</strong></td>
            <td>
                <button class="btn-view" onclick="viewUser('${user.username}')">查看</button>
            </td>
        </tr>
    `).join('');
}

// 显示最近活动
function displayRecentActivity(activities) {
    const list = document.getElementById('activityList');
    const countEl = document.getElementById('activityCount');
    
    // 更新活动计数
    if (countEl) {
        countEl.textContent = `共 ${activities.length} 条记录`;
    }
    
    if (activities.length === 0) {
        list.innerHTML = '<p class="no-data">暂无活动记录</p>';
        if (countEl) countEl.textContent = '无记录';
        return;
    }
    
    list.innerHTML = activities.map(activity => {
        // 根据活动类型设置不同的样式
        let iconHtml, activityClass, typeLabel, typeColor;
        
        if (activity.icon === 'user') {
            iconHtml = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>';
            activityClass = 'activity-user';
            typeLabel = '新注册';
            typeColor = '#667eea';
        } else if (activity.icon === 'quiz') {
            iconHtml = '<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M9 11l3 3L22 4"></path><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"></path></svg>';
            activityClass = 'activity-quiz';
            typeLabel = '答题记录';
            typeColor = '#4caf50';
        } else {
            iconHtml = '📝';
            activityClass = 'activity-default';
            typeLabel = '活动';
            typeColor = '#999';
        }
        
        // 解析标题和详情
        let userName = '';
        let actionText = '';
        let scoreText = '';
        
        if (activity.icon === 'user') {
            const match = activity.title.match(/新用户注册: (.+)/);
            userName = match ? match[1] : '未知用户';
            actionText = '注册了账号';
        } else if (activity.icon === 'quiz') {
            const match = activity.title.match(/答题完成: (.+)得分 (\d+)/);
            if (match) {
                userName = match[1];
                scoreText = match[2];
                actionText = '完成答题';
            }
        }
        
        return `
            <div class="activity-item ${activityClass}">
                <div class="activity-icon-wrapper">
                    <div class="activity-icon">${iconHtml}</div>
                </div>
                <div class="activity-content">
                    <div class="activity-header">
                        <span class="activity-type-badge" style="background: ${typeColor}20; color: ${typeColor}">
                            ${typeLabel}
                        </span>
                        <span class="activity-time">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                                <circle cx="12" cy="12" r="10"></circle>
                                <polyline points="12 6 12 12 16 14"></polyline>
                            </svg>
                            ${formatActivityTime(activity.time)}
                        </span>
                    </div>
                    <div class="activity-body">
                        <span class="activity-user">${userName}</span>
                        <span class="activity-action">${actionText}</span>
                        ${scoreText ? `<span class="activity-score">得分 <strong>${scoreText}</strong></span>` : ''}
                    </div>
                </div>
            </div>
        `;
    }).join('');
}

// 格式化活动时间
function formatActivityTime(timeStr) {
    const activityTime = new Date(timeStr);
    const now = new Date();
    const diffMs = now - activityTime;
    const diffMins = Math.floor(diffMs / 60000);
    const diffHours = Math.floor(diffMs / 3600000);
    const diffDays = Math.floor(diffMs / 86400000);
    
    if (diffMins < 1) {
        return '刚刚';
    } else if (diffMins < 60) {
        return `${diffMins}分钟前`;
    } else if (diffHours < 24) {
        return `${diffHours}小时前`;
    } else if (diffDays < 7) {
        return `${diffDays}天前`;
    } else {
        return timeStr.split(' ')[0]; // 返回日期部分
    }
}

// 查看用户详情
function viewUser(username) {
    const user = usersData.find(u => u.username === username);
    if (user) {
        alert(`用户详情：\n\n用户名: ${user.username}\n邮箱: ${user.email}\n答题次数: ${user.quiz_count || 0}\n总得分: ${user.score || 0}\n注册时间: ${user.created_at || '未知'}\n最后登录: ${user.last_login || '从未登录'}`);
    }
}

// 搜索功能
const searchInput = document.getElementById('searchInput');
if (searchInput) {
    searchInput.addEventListener('input', function() {
        const keyword = this.value.toLowerCase();
        const filteredUsers = usersData.filter(user => 
            user.username.toLowerCase().includes(keyword) ||
            user.email.toLowerCase().includes(keyword)
        );
        displayUsersTable(filteredUsers);
    });
}

// 题目管理相关功能
let categoriesData = [];
let questionsData = [];
let filteredQuestionsData = [];

// 加载题目数据
function loadQuestionsData() {
    fetch('/api/admin/questions')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                questionsData = data.questions || [];
                filteredQuestionsData = questionsData; // 初始化筛选数据
                displayQuestionsTable(filteredQuestionsData);
                updateFilterStats(filteredQuestionsData.length);
                
                // 显示筛选面板
                document.getElementById('filtersPanel').style.display = 'flex';
            } else {
                console.error('加载题目失败:', data.message);
                document.getElementById('questionsTableBody').innerHTML = 
                    '<tr><td colspan="6" class="no-data">加载题目失败</td></tr>';
            }
        })
        .catch(error => {
            console.error('加载题目数据失败:', error);
            document.getElementById('questionsTableBody').innerHTML = 
                '<tr><td colspan="6" class="no-data">网络错误</td></tr>';
        });
}

// 加载分类数据（用于表单）
function loadCategoriesForForm() {
    fetch('/api/admin/categories')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                categoriesData = data.categories || [];
                populateCategoriesSelect();
                populateFilterCategoriesSelect();
            }
        })
        .catch(error => {
            console.error('加载分类数据失败:', error);
        });
}

// 填充分类选择框
function populateCategoriesSelect() {
    const select = document.getElementById('category');
    if (select && categoriesData.length > 0) {
        select.innerHTML = '<option value="">请选择分类</option>' +
            categoriesData.map(cat => 
                `<option value="${cat.id}">${cat.name}</option>`
            ).join('');
    }
}

// 填充筛选器分类选择框
function populateFilterCategoriesSelect() {
    const select = document.getElementById('filterCategory');
    if (select && categoriesData.length > 0) {
        select.innerHTML = '<option value="">全部分类</option>' +
            categoriesData.map(cat => 
                `<option value="${cat.name}">${cat.name}</option>`
            ).join('');
    }
}

// 显示题目表格
function displayQuestionsTable(questions) {
    const tbody = document.getElementById('questionsTableBody');
    const container = document.getElementById('questionsTableContainer');
    
    if (questions.length === 0) {
        tbody.innerHTML = '<tr><td colspan="6" class="no-data">暂无题目，点击"添加题目"按钮开始添加</td></tr>';
        container.style.display = 'block';
        return;
    }
    
    tbody.innerHTML = questions.map((q, index) => `
        <tr>
            <td><div class="question-title">${q.title}</div></td>
            <td>
                <span class="question-type-badge ${q.question_type === 'fill_in_blank' ? 'type-fill' : 'type-choice'}">
                    ${q.question_type === 'fill_in_blank' ? '填空题' : '选择题'}
                </span>
            </td>
            <td>${q.category_name || '未分类'}</td>
            <td>
                <span class="difficulty-badge difficulty-${q.difficulty}">
                    ${getDifficultyText(q.difficulty)}
                </span>
            </td>
            <td><strong class="correct-answer">${getCorrectAnswerDisplay(q)}</strong></td>
            <td>
                <button class="btn-view" onclick="viewQuestionDetail(${index})">查看详情</button>
                <button class="btn-delete" onclick="deleteQuestion(${q.id}, ${index})">删除</button>
            </td>
        </tr>
    `).join('');
    
    container.style.display = 'block';
}

// 获取难度文本
function getDifficultyText(difficulty) {
    const map = {
        'easy': '简单',
        'medium': '中等',
        'hard': '困难'
    };
    return map[difficulty] || difficulty;
}

// 获取正确答案显示
function getCorrectAnswerDisplay(question) {
    if (question.question_type === 'fill_in_blank') {
        return question.fill_in_answer || question.correct_answer || '未设置';
    } else {
        return question.correct_answer || '未设置';
    }
}

// 删除题目
function deleteQuestion(questionId, index) {
    if (!confirm('确定要删除这道题目吗？')) {
        return;
    }
    
    fetch(`/api/admin/questions/${questionId}`, {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('题目删除成功');
            loadQuestionsData();
        } else {
            alert('删除失败: ' + data.message);
        }
    })
    .catch(error => {
        console.error('删除题目失败:', error);
        alert('删除失败: 网络错误');
    });
}

// 显示/隐藏添加题目表单
function toggleAddQuestionForm() {
    const form = document.getElementById('addQuestionForm');
    const table = document.getElementById('questionsTableContainer');
    
    if (form.style.display === 'none') {
        form.style.display = 'block';
        table.style.display = 'none';
        document.getElementById('questionForm').reset();
    } else {
        form.style.display = 'none';
        table.style.display = 'block';
    }
}

// 绑定添加题目按钮
document.addEventListener('DOMContentLoaded', function() {
    const addBtn = document.getElementById('addQuestionBtn');
    const cancelBtn = document.getElementById('cancelQuestionBtn');
    const form = document.getElementById('questionForm');
    
    if (addBtn) {
        addBtn.addEventListener('click', function() {
            toggleAddQuestionForm();
        });
    }
    
    if (cancelBtn) {
        cancelBtn.addEventListener('click', function() {
            toggleAddQuestionForm();
        });
    }
    
    if (form) {
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            submitQuestion();
        });
    }

    // 批量导入功能
    setupBatchImport();
});

// 提交题目
function submitQuestion() {
    const form = document.getElementById('questionForm');
    const formData = new FormData(form);
    
    const data = {
        category_id: parseInt(formData.get('category')),
        title: formData.get('title'),
        question_type: formData.get('question_type') || 'multiple_choice',
        option_a: formData.get('option_a'),
        option_b: formData.get('option_b'),
        option_c: formData.get('option_c') || null,
        option_d: formData.get('option_d') || null,
        correct_answer: formData.get('correct_answer'),
        difficulty: formData.get('difficulty'),
        explanation: formData.get('explanation') || '',
        // 填空题字段
        fill_in_answer: formData.get('fill_in_answer') || null,
        fill_in_keywords: formData.get('fill_in_keywords') || null,
        // 图片字段
        question_image: formData.get('question_image') || null,
        option_a_image: formData.get('option_a_image') || null,
        option_b_image: formData.get('option_b_image') || null,
        option_c_image: formData.get('option_c_image') || null,
        option_d_image: formData.get('option_d_image') || null,
        explanation_image: formData.get('explanation_image') || null
    };
    
    // 验证必填项
    if (!data.category_id || !data.title) {
        alert('请填写所有必填项');
        return;
    }
    
    // 根据题目类型验证不同的必填项
    if (data.question_type === 'fill_in_blank') {
        if (!data.fill_in_answer) {
            alert('请填写填空题答案');
            return;
        }
    } else {
        if (!data.option_a || !data.option_b || !data.correct_answer) {
            alert('请填写所有必填项');
            return;
        }
    }
    
    // 禁用提交按钮
    const submitBtn = document.querySelector('#questionForm .btn-submit');
    submitBtn.disabled = true;
    submitBtn.textContent = '提交中...';
    
    fetch('/api/admin/questions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            alert('题目添加成功！');
            form.reset();
            clearAllImages();  // 清空图片预览
            toggleAddQuestionForm();
            loadQuestionsData();
        } else {
            alert('添加失败: ' + result.message);
        }
        submitBtn.disabled = false;
        submitBtn.textContent = '添加题目';
    })
    .catch(error => {
        console.error('提交题目失败:', error);
        alert('提交失败: 网络错误');
        submitBtn.disabled = false;
        submitBtn.textContent = '添加题目';
    });
}

// ========== 批量导入功能 ==========

function setupBatchImport() {
    const batchBtn = document.getElementById('batchImportBtn');
    const cancelBatchBtn = document.getElementById('cancelBatchBtn');
    const cancelFileBatchBtn = document.getElementById('cancelFileBatchBtn');
    const importJsonBtn = document.getElementById('importJsonBtn');
    const importFileBtn = document.getElementById('importFileBtn');
    
    // 批量导入按钮
    if (batchBtn) {
        batchBtn.addEventListener('click', function() {
            toggleBatchImportPanel();
        });
    }
    
    // 取消按钮
    if (cancelBatchBtn) {
        cancelBatchBtn.addEventListener('click', function() {
            toggleBatchImportPanel();
        });
    }
    
    if (cancelFileBatchBtn) {
        cancelFileBatchBtn.addEventListener('click', function() {
            toggleBatchImportPanel();
        });
    }
    
    // JSON导入
    if (importJsonBtn) {
        importJsonBtn.addEventListener('click', function() {
            importFromJSON();
        });
    }
    
    // 文件导入
    if (importFileBtn) {
        importFileBtn.addEventListener('click', function() {
            importFromFile();
        });
    }
    
    // Tab切换
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const tab = this.getAttribute('data-tab');
            switchImportTab(tab);
        });
    });
}

// 切换批量导入面板
function toggleBatchImportPanel() {
    const panel = document.getElementById('batchImportPanel');
    const form = document.getElementById('addQuestionForm');
    const table = document.getElementById('questionsTableContainer');
    
    if (panel.style.display === 'none') {
        panel.style.display = 'block';
        form.style.display = 'none';
        table.style.display = 'none';
        // 清空输入
        document.getElementById('jsonInput').value = '';
        document.getElementById('jsonFile').value = '';
    } else {
        panel.style.display = 'none';
        table.style.display = 'block';
    }
}

// 切换导入标签页
function switchImportTab(tab) {
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
    });
    document.querySelectorAll('.import-tab-content').forEach(content => {
        content.classList.remove('active');
    });
    
    document.querySelector(`[data-tab="${tab}"]`).classList.add('active');
    document.getElementById(tab + 'Tab').classList.add('active');
}

// 从JSON导入
function importFromJSON() {
    const jsonInput = document.getElementById('jsonInput').value.trim();
    
    if (!jsonInput) {
        alert('请输入JSON数据');
        return;
    }
    
    let data;
    try {
        data = JSON.parse(jsonInput);
    } catch (e) {
        alert('JSON格式错误，请检查格式：' + e.message);
        return;
    }
    
    if (!data.questions || !Array.isArray(data.questions)) {
        alert('JSON数据必须包含questions数组');
        return;
    }
    
    if (data.questions.length === 0) {
        alert('题目列表为空');
        return;
    }
    
    if (!confirm(`确定要导入 ${data.questions.length} 道题目吗？`)) {
        return;
    }
    
    // 显示进度
    showProgress('正在导入题目，请稍候...');
    
    const importBtn = document.getElementById('importJsonBtn');
    importBtn.disabled = true;
    importBtn.textContent = '导入中...';
    
    fetch('/api/admin/questions/batch', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(result => {
        hideProgress();
        
        if (result.success) {
            let message = `导入完成！\n成功：${result.success_count}道\n失败：${result.error_count}道`;
            
            if (result.errors && result.errors.length > 0) {
                message += '\n\n错误详情：\n' + result.errors.join('\n');
            }
            
            alert(message);
            
            // 清空输入并关闭面板
            document.getElementById('jsonInput').value = '';
            toggleBatchImportPanel();
            
            // 重新加载题目列表
            loadQuestionsData();
        } else {
            alert('导入失败：' + result.message);
        }
        
        importBtn.disabled = false;
        importBtn.textContent = '导入题目';
    })
    .catch(error => {
        hideProgress();
        console.error('导入失败:', error);
        alert('导入失败：网络错误');
        importBtn.disabled = false;
        importBtn.textContent = '导入题目';
    });
}

// 从文件导入
function importFromFile() {
    const fileInput = document.getElementById('jsonFile');
    const file = fileInput.files[0];
    
    if (!file) {
        alert('请选择文件');
        return;
    }
    
    if (!file.name.endsWith('.json')) {
        alert('只支持JSON文件');
        return;
    }
    
    if (!confirm(`确定要导入文件 "${file.name}" 吗？`)) {
        return;
    }
    
    // 显示进度
    showProgress('正在上传并导入文件，请稍候...');
    
    const importBtn = document.getElementById('importFileBtn');
    importBtn.disabled = true;
    importBtn.textContent = '导入中...';
    
    const formData = new FormData();
    formData.append('file', file);
    
    fetch('/api/admin/questions/import-json', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(result => {
        hideProgress();
        
        if (result.success) {
            let message = `导入完成！\n成功：${result.success_count}道\n失败：${result.error_count}道`;
            
            if (result.errors && result.errors.length > 0) {
                message += '\n\n错误详情（前10条）：\n' + result.errors.join('\n');
            }
            
            alert(message);
            
            // 清空文件选择并关闭面板
            fileInput.value = '';
            toggleBatchImportPanel();
            
            // 重新加载题目列表
            loadQuestionsData();
        } else {
            alert('导入失败：' + result.message);
        }
        
        importBtn.disabled = false;
        importBtn.textContent = '上传并导入';
    })
    .catch(error => {
        hideProgress();
        console.error('导入失败:', error);
        alert('导入失败：网络错误');
        importBtn.disabled = false;
        importBtn.textContent = '上传并导入';
    });
}

// 显示进度提示
function showProgress(message) {
    const modal = document.getElementById('progressModal');
    const info = document.getElementById('progressInfo');
    info.innerHTML = `<p>${message}</p>`;
    modal.style.display = 'flex';
}

// 隐藏进度提示
function hideProgress() {
    const modal = document.getElementById('progressModal');
    modal.style.display = 'none';
}

// 显示示例JSON
function showExampleJSON() {
    const example = {
        "questions": [
            {
                "category_id": 1,
                "title": "Python中哪个关键字用于定义函数？",
                "option_a": "function",
                "option_b": "def",
                "option_c": "func",
                "option_d": "define",
                "correct_answer": "B",
                "explanation": "Python使用def关键字来定义函数",
                "difficulty": "easy"
            },
            {
                "category_id": 1,
                "title": "以下哪个不是Python的数据类型？",
                "option_a": "list",
                "option_b": "tuple",
                "option_c": "array",
                "option_d": "dict",
                "correct_answer": "C",
                "explanation": "array不是Python内置数据类型",
                "difficulty": "medium"
            }
        ]
    };
    
    const jsonStr = JSON.stringify(example, null, 2);
    document.getElementById('jsonInput').value = jsonStr;
    alert('已填充示例数据，您可以直接导入或修改后导入');
}

// ========== 题目筛选功能 ==========

// 应用筛选
function applyQuestionFilter() {
    const categoryFilter = document.getElementById('filterCategory').value;
    const difficultyFilter = document.getElementById('filterDifficulty').value;
    
    filteredQuestionsData = questionsData.filter(q => {
        let matchCategory = true;
        let matchDifficulty = true;
        
        if (categoryFilter) {
            matchCategory = q.category_name === categoryFilter;
        }
        
        if (difficultyFilter) {
            matchDifficulty = q.difficulty === difficultyFilter;
        }
        
        return matchCategory && matchDifficulty;
    });
    
    displayQuestionsTable(filteredQuestionsData);
    updateFilterStats(filteredQuestionsData.length);
}

// 重置筛选
function resetQuestionFilter() {
    document.getElementById('filterCategory').value = '';
    document.getElementById('filterDifficulty').value = '';
    filteredQuestionsData = questionsData;
    displayQuestionsTable(filteredQuestionsData);
    updateFilterStats(filteredQuestionsData.length);
}

// 更新筛选统计
function updateFilterStats(count) {
    document.getElementById('filterStats').innerHTML = 
        `共 <strong>${count}</strong> 道题目`;
}

// 设置筛选事件
document.addEventListener('DOMContentLoaded', function() {
    const applyFilterBtn = document.getElementById('applyFilterBtn');
    const resetFilterBtn = document.getElementById('resetFilterBtn');
    
    if (applyFilterBtn) {
        applyFilterBtn.addEventListener('click', applyQuestionFilter);
    }
    
    if (resetFilterBtn) {
        resetFilterBtn.addEventListener('click', resetQuestionFilter);
    }
});

// ========== 题目详情查看功能 ==========

// 查看题目详情
function viewQuestionDetail(index) {
    const question = filteredQuestionsData[index];
    if (!question) return;
    
    // 填充详情数据
    document.getElementById('detailQuestionCategory').textContent = question.category_name || '未分类';
    
    const difficultyBadge = document.getElementById('detailQuestionDifficulty');
    difficultyBadge.textContent = getDifficultyText(question.difficulty);
    difficultyBadge.className = `difficulty-badge difficulty-${question.difficulty}`;
    
    // 显示题目和题目图片（支持markdown）
    const titleEl = document.getElementById('detailQuestionTitle');
    titleEl.innerHTML = renderMarkdown(question.title);
    
    // 在题目标题区域显示图片
    const questionTextEl = titleEl.parentElement;
    if (questionTextEl) {
        // 清除所有可能存在的旧图片
        const existingImgs = questionTextEl.querySelectorAll('.question-image-detail');
        existingImgs.forEach(img => img.remove());
        
        if (question.question_image) {
            const img = document.createElement('img');
            img.src = question.question_image;
            img.className = 'question-image-detail';
            img.style.cssText = 'max-width: 100%; max-height: 300px; margin-top: 15px; border-radius: 8px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);';
            questionTextEl.appendChild(img);
        }
    }
    
    // 根据题目类型显示不同的选项/答案区域
    const optionsContainer = document.getElementById('detailQuestionOptions');
    const answerBlock = document.querySelector('.answer-block');
    const optionsBlock = document.querySelector('.question-block:has(#detailQuestionOptions)');
    
    if (question.question_type === 'fill_in_blank') {
        // 填空题：隐藏选项区域，重新设计答案区域
        if (optionsBlock) {
            optionsBlock.style.display = 'none';
        }
        
        // 重新设计整个答案区域
        answerBlock.innerHTML = `
            <div class="block-title">📝 填空题答案</div>
            <div class="fill-in-answer-section">
                <div class="fill-in-main-answer">
                    <div class="fill-in-answer-label">标准答案</div>
                    <div class="fill-in-answer-content">${question.fill_in_answer || '未设置'}</div>
                </div>
                ${question.fill_in_keywords ? `
                    <div class="fill-in-keywords-section">
                        <div class="fill-in-keywords-label">可接受关键词</div>
                        <div class="fill-in-keywords-content">${question.fill_in_keywords}</div>
                    </div>
                ` : ''}
                <div class="fill-in-note">
                    <i class="note-icon">💡</i>
                    <span>系统会自动匹配标准答案和关键词，支持模糊匹配</span>
                </div>
            </div>
        `;
    } else {
        // 选择题：显示选项区域，使用原有逻辑
        if (optionsBlock) {
            optionsBlock.style.display = 'block';
        }
        
        // 恢复答案区域的原始结构
        answerBlock.innerHTML = `
            <div class="block-title">正确答案</div>
            <div class="answer-display">
                <span class="answer-badge" id="detailCorrectAnswer">A</span>
            </div>
        `;
        
        // 填充选项（包含图片，支持markdown）
        const optionsHtml = [];
        if (question.option_a) {
            const optionImage = question.option_a_image ? 
                `<img src="${question.option_a_image}" style="max-width: 100%; max-height: 150px; margin-top: 8px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">` : '';
            optionsHtml.push(`
                <div class="option-item ${question.correct_answer === 'A' ? 'correct-option' : ''}">
                    <span class="option-label">A</span>
                    <div class="option-text">
                        ${renderMarkdown(question.option_a)}
                        ${optionImage}
                    </div>
                </div>
            `);
        }
        if (question.option_b) {
            const optionImage = question.option_b_image ? 
                `<img src="${question.option_b_image}" style="max-width: 100%; max-height: 150px; margin-top: 8px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">` : '';
            optionsHtml.push(`
                <div class="option-item ${question.correct_answer === 'B' ? 'correct-option' : ''}">
                    <span class="option-label">B</span>
                    <div class="option-text">
                        ${renderMarkdown(question.option_b)}
                        ${optionImage}
                    </div>
                </div>
            `);
        }
        if (question.option_c) {
            const optionImage = question.option_c_image ? 
                `<img src="${question.option_c_image}" style="max-width: 100%; max-height: 150px; margin-top: 8px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">` : '';
            optionsHtml.push(`
                <div class="option-item ${question.correct_answer === 'C' ? 'correct-option' : ''}">
                    <span class="option-label">C</span>
                    <div class="option-text">
                        ${renderMarkdown(question.option_c)}
                        ${optionImage}
                    </div>
                </div>
            `);
        }
        if (question.option_d) {
            const optionImage = question.option_d_image ? 
                `<img src="${question.option_d_image}" style="max-width: 100%; max-height: 150px; margin-top: 8px; border-radius: 6px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">` : '';
            optionsHtml.push(`
                <div class="option-item ${question.correct_answer === 'D' ? 'correct-option' : ''}">
                    <span class="option-label">D</span>
                    <div class="option-text">
                        ${renderMarkdown(question.option_d)}
                        ${optionImage}
                    </div>
                </div>
            `);
        }
        
        optionsContainer.innerHTML = optionsHtml.join('');
        // 在重建HTML后重新获取答案容器元素并设置内容
        const answerContainer = document.getElementById('detailCorrectAnswer');
        if (answerContainer) {
            answerContainer.textContent = question.correct_answer;
        }
    }
    
    // 显示解析和解析图片（支持markdown）
    const explanationEl = document.getElementById('detailExplanation');
    explanationEl.innerHTML = renderMarkdown(question.explanation || '暂无解析');
    
    // 显示解析图片
    const explanationBlockEl = explanationEl.parentElement;
    if (explanationBlockEl) {
        // 清除所有可能存在的旧图片
        const existingImgs = explanationBlockEl.querySelectorAll('.explanation-image-detail');
        existingImgs.forEach(img => img.remove());
        
        if (question.explanation_image) {
            const img = document.createElement('img');
            img.src = question.explanation_image;
            img.className = 'explanation-image-detail';
            img.style.cssText = 'max-width: 100%; max-height: 250px; margin-top: 15px; border-radius: 8px; box-shadow: 0 3px 10px rgba(0,0,0,0.1);';
            explanationBlockEl.appendChild(img);
        }
    }
    
    // 显示弹窗
    document.getElementById('questionDetailModal').style.display = 'flex';
    
    // 渲染数学公式
    setTimeout(() => {
        const modal = document.getElementById('questionDetailModal');
        renderMath(modal);
    }, 100);
}

// 关闭题目详情弹窗
function closeQuestionDetailModal() {
    const modal = document.getElementById('questionDetailModal');
    modal.style.display = 'none';
    
    // 清理所有图片，防止图片串位
    const allDetailImages = modal.querySelectorAll('.question-image-detail, .explanation-image-detail');
    allDetailImages.forEach(img => img.remove());
}

// 设置题目详情弹窗关闭事件
document.addEventListener('DOMContentLoaded', function() {
    const closeBtn = document.getElementById('closeQuestionDetail');
    const closeDetailBtn = document.getElementById('closeDetailBtn');
    
    if (closeBtn) {
        closeBtn.addEventListener('click', closeQuestionDetailModal);
    }
    
    if (closeDetailBtn) {
        closeDetailBtn.addEventListener('click', closeQuestionDetailModal);
    }
    
    // 点击弹窗外部（overlay）关闭
    const modal = document.getElementById('questionDetailModal');
    if (modal) {
        modal.addEventListener('click', function(event) {
            // 如果点击的是modal本身或overlay，关闭弹窗
            if (event.target === modal || event.target.classList.contains('modal-overlay')) {
                closeQuestionDetailModal();
            }
        });
    }
});

// ========== 图片上传功能 ==========

// 设置图片上传
function setupImageUploads() {
    const imageFields = [
        { fileId: 'questionImageFile', hiddenId: 'question_image', previewId: 'questionImagePreview' },
        { fileId: 'optionAImageFile', hiddenId: 'option_a_image', previewId: 'optionAImagePreview' },
        { fileId: 'optionBImageFile', hiddenId: 'option_b_image', previewId: 'optionBImagePreview' },
        { fileId: 'optionCImageFile', hiddenId: 'option_c_image', previewId: 'optionCImagePreview' },
        { fileId: 'optionDImageFile', hiddenId: 'option_d_image', previewId: 'optionDImagePreview' },
        { fileId: 'explanationImageFile', hiddenId: 'explanation_image', previewId: 'explanationImagePreview' }
    ];
    
    imageFields.forEach(field => {
        const fileInput = document.getElementById(field.fileId);
        if (fileInput) {
            fileInput.addEventListener('change', function(e) {
                handleImageUpload(e.target.files[0], field.hiddenId, field.previewId);
            });
        }
    });
}

// 处理图片上传
async function handleImageUpload(file, hiddenFieldId, previewId) {
    if (!file) return;
    
    // 验证文件类型
    const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
    if (!allowedTypes.includes(file.type)) {
        alert('只支持 PNG、JPEG、GIF、WebP 格式的图片');
        return;
    }
    
    // 验证文件大小（5MB）
    if (file.size > 5 * 1024 * 1024) {
        alert('图片大小不能超过 5MB');
        return;
    }
    
    // 显示加载提示
    const previewDiv = document.getElementById(previewId);
    previewDiv.innerHTML = '<div class="loading-text">上传中...</div>';
    previewDiv.classList.add('active');
    
    try {
        const formData = new FormData();
        formData.append('image', file);
        
        const response = await fetch('/api/admin/upload-image', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            // 保存图片URL到隐藏字段
            document.getElementById(hiddenFieldId).value = result.image_url;
            
            // 显示预览
            showImagePreview(result.image_url, previewId, hiddenFieldId);
        } else {
            alert('上传失败：' + result.message);
            previewDiv.innerHTML = '';
            previewDiv.classList.remove('active');
        }
    } catch (error) {
        console.error('上传图片失败:', error);
        alert('上传失败，请重试');
        previewDiv.innerHTML = '';
        previewDiv.classList.remove('active');
    }
}

// 显示图片预览
function showImagePreview(imageUrl, previewId, hiddenFieldId) {
    const previewDiv = document.getElementById(previewId);
    previewDiv.innerHTML = `
        <div class="image-preview-container">
            <img src="${imageUrl}" alt="预览">
            <button type="button" class="btn-delete-image" onclick="deleteUploadedImage('${imageUrl}', '${previewId}', '${hiddenFieldId}')">
                ×
            </button>
        </div>
    `;
    previewDiv.classList.add('active');
}

// 删除上传的图片
async function deleteUploadedImage(imageUrl, previewId, hiddenFieldId) {
    if (!confirm('确定要删除这张图片吗？')) return;
    
    try {
        const response = await fetch('/api/admin/delete-image', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ image_url: imageUrl })
        });
        
        const result = await response.json();
        
        if (result.success) {
            // 清空隐藏字段和预览
            document.getElementById(hiddenFieldId).value = '';
            const previewDiv = document.getElementById(previewId);
            previewDiv.innerHTML = '';
            previewDiv.classList.remove('active');
        } else {
            alert('删除失败：' + result.message);
        }
    } catch (error) {
        console.error('删除图片失败:', error);
        alert('删除失败，请重试');
    }
}

// 清空所有图片
function clearAllImages() {
    const imageFields = [
        { hiddenId: 'question_image', previewId: 'questionImagePreview' },
        { hiddenId: 'option_a_image', previewId: 'optionAImagePreview' },
        { hiddenId: 'option_b_image', previewId: 'optionBImagePreview' },
        { hiddenId: 'option_c_image', previewId: 'optionCImagePreview' },
        { hiddenId: 'option_d_image', previewId: 'optionDImagePreview' },
        { hiddenId: 'explanation_image', previewId: 'explanationImagePreview' }
    ];
    
    imageFields.forEach(field => {
        const hiddenField = document.getElementById(field.hiddenId);
        const previewDiv = document.getElementById(field.previewId);
        if (hiddenField) hiddenField.value = '';
        if (previewDiv) {
            previewDiv.innerHTML = '';
            previewDiv.classList.remove('active');
        }
    });
}

// 题目类型切换函数
function toggleQuestionType() {
    const questionType = document.getElementById('question_type').value;
    const multipleChoiceFields = document.getElementById('multipleChoiceFields');
    const fillInBlankFields = document.getElementById('fillInBlankFields');
    const multipleChoiceAnswer = document.getElementById('multipleChoiceAnswer');
    
    if (questionType === 'fill_in_blank') {
        // 显示填空题字段，隐藏选择题字段
        multipleChoiceFields.style.display = 'none';
        fillInBlankFields.style.display = 'block';
        multipleChoiceAnswer.style.display = 'none';
        
        // 清空选择题字段的required属性
        document.getElementById('option_a').removeAttribute('required');
        document.getElementById('option_b').removeAttribute('required');
        document.getElementById('correct_answer').removeAttribute('required');
        
        // 为填空题字段添加required属性
        document.getElementById('fill_in_answer').setAttribute('required', 'required');
    } else {
        // 显示选择题字段，隐藏填空题字段
        multipleChoiceFields.style.display = 'block';
        fillInBlankFields.style.display = 'none';
        multipleChoiceAnswer.style.display = 'block';
        
        // 为选择题字段添加required属性
        document.getElementById('option_a').setAttribute('required', 'required');
        document.getElementById('option_b').setAttribute('required', 'required');
        document.getElementById('correct_answer').setAttribute('required', 'required');
        
        // 清空填空题字段的required属性
        document.getElementById('fill_in_answer').removeAttribute('required');
    }
}
